package com.suxin.websocket.config;

import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname ThreadPoolBuilder
 * @description [  ]
 * @date 2022/3/24 14:31
 */
public class ThreadPoolBuilder {

    private static Integer core = Runtime.getRuntime().availableProcessors() + 1;


    public static ThreadPoolExecutor defaultBuild() {
        return build(
                core, core + 1
        );
    }

    public static ThreadPoolExecutor build(int corePoolSize, int maximumPoolSize) {
        return build(
                corePoolSize,
                maximumPoolSize,
                100L
        );
    }

    public static ThreadPoolExecutor build(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        return build(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                new ArrayBlockingQueue<>(100)
        );
    }

    public static ThreadPoolExecutor build(int corePoolSize, int maximumPoolSize,
                                           long keepAliveTime,
                                           BlockingQueue<Runnable> workQueue) {
        return build(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                workQueue,
                "work-thread-"
        );
    }

    public static ThreadPoolExecutor build(int corePoolSize,
                                           int maximumPoolSize,
                                           long keepAliveTime,
                                           BlockingQueue<Runnable> workQueue,
                                           String threadNamePrefix) {
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                workQueue,
                new CustomizableThreadFactory(threadNamePrefix)
        );
    }

}